/**
 * Created by Administrator on 2017/7/24.
 */

    var studentStudy = new Object();
    studentStudy.study_time = 0;
    studentStudy.video_id = "";
    studentStudy.video_time = 0;
    studentStudy.doc_time = 0;
    studentStudy.coverINfoUrl = appPath + "/static/global/images/course/course_cover_info.png";
    var swfTime;
    // 初始化
    studentStudy.init = function(basePath, projectId, courseId, userId, source){
        //console.log("basePath="+basePath);console.log("projectId="+projectId);console.log("courseId="+courseId);console.log("userId="+userId);console.log("source="+source);
        studentStudy.basePath = basePath;
        studentStudy.projectId = projectId;
        studentStudy.courseId = courseId;
        studentStudy.userId = userId;
        studentStudy.source = source;
        studentStudy.isClosed = 0;

        // 初始化事件
        studentStudy.initEvent();
        // 获取课程基本信息
        studentStudy.getCourse();
    };

    studentStudy.initEvent = function () {
        // studentStudy.messenger.addTarget(window.opener, 'parent1');

        // 点击返回主页
        $(".back").bind("click", function () {
            // send to server for mark time
            window.open('', '_self', '');
            window.opener = null;
            window.close();
        });

        studentStudy.timer = null;
        studentStudy.speed = 250;
        studentStudy.time = 0;
        studentStudy.options = {
            'techOrder':['html5'],
            controlBar : {
                volumeMenuButton : {
                    inline :false,
                    vertical : true
                }
            }
        };
        studentStudy.player = videojs("video", studentStudy.options, function(){
           videojs.log('your player is ready !!!');
            this.on("loadstart", function () {
                videojs.log('your player is loadstart !!!');
            });

            this.on("seeking", function () {
                videojs.log('your player is seeking !!!');
            });

            this.on("seeked", function () {
                videojs.log('your player is seeked !!!');
            });
            this.on('loadedalldate',function(){
                videojs.log( 'loadedalldate' );
            });

            this.on("waiting", function () {
                videojs.log('your player is waiting !!!');
            });

            this.on("timeupdate", function () {
                 videojs.log('your player is timeupdate !!!');
               /* studentStudy.time += 0.25;
                $("#study_time").html(studentStudy.formatSeconds(parseInt(studentStudy.time)));*/

                // var currentTime = this.currentTime(); // 获取播放进度
            });
            this.on('progress',function(){
                //videojs.log('your player is progress !!!');
            });

            this.on("ended", function () {
                videojs.log('your player is over !!!');
                // 切换到下一个视频
                message.add("温馨提示:即将自动播放下一个视频", "normal");
                var len = $("#show_list_video li a[class='active']").parent().next().length;
                studentStudy.video_time = 0;
                if(len >0 ){
                $("#show_list_video li a[class='active']").parent().next().find("a:eq(0)").trigger("click");
                }else{
                    $("#show_list_video li a[class='active']").parent().parent().find("li:eq(0)").find("a").trigger("click");
                }

            });




            this.on("play", function () {
                videojs.log('your player is play !!!');

            });

            this.on("pause", function () {
                videojs.log('your player is pause !!!');
            });
        });


    }

    studentStudy.plusTime = function () {
        if(studentStudy.time && studentStudy.time != 0){
            //关闭页面记录视频播放位置
            studentStudy.savePosition();
            setCookie('messenger_parent_msg', "study_refresh");
            var fromData = new FormData();
            fromData.append("project_id",studentStudy.projectId);
            fromData.append("course_id",studentStudy.courseId);
            fromData.append("user_id",studentStudy.userId);
            fromData.append("source",studentStudy.source);
            fromData.append("study_time",parseInt(studentStudy.time));

            navigator.sendBeacon(studentStudy.basePath + "student/study/plusTime", fromData);

            /* var params = {
                 'project_id': studentStudy.projectId,
                 'course_id': studentStudy.courseId,
                 'user_id': studentStudy.userId,
                 //'user_id': "132456798",
                 'source': studentStudy.source,
                 'study_time': parseInt(studentStudy.time)
             };
             // onlineStudy用于防止ajax重复发请求
             if(studentStudy.isClosed != 1){
                 $.ajax({
                     url: studentStudy.basePath + "student/study/plusTime",
                     data: params,
                     type: "post",
                     async : false,
                     dataType:"json",
                     success:function(data) {
                         studentStudy.isClosed = 1;
                     },
                     complete:function(){
                         // studentStudy.messenger.targets['parent1'].send("我特么学完了");

                         window.open('', '_self', '');
                         window.opener = null;
                         window.close();
                     },
                     error:function (xhr) {
                         var test = xhr.statusText;
                        // console.log(xhr.responseText);

                     }
                 });
             }*/
        }else{
            common.study_messenger_send("study_check_is_close");
        }
    };

    studentStudy.getCourse = function(){
        var params = {
            'courseId': studentStudy.courseId
        };
        $.ajax({
            url: studentStudy.basePath + "popup/getCourse",
            data: params,
            type: "post",
            dataType:"json",
            success:function(data) {
                //console.log(data);
                var code = data.code;
                if("10000" == code){
                    var course = data['result'];
                    if(null == course || typeof (course) == 'undefined') {
                        message.add("查询课程信息失败", "error");
                        $("#show_list_video").empty().html("<li class=\"empty\">暂无视频</li>");
                        $("#show_list_doc").empty().html("<li class=\"empty\">暂无文档</li>");
                        return;
                    }
                    var courseName = course['varName'];
                    var courseDesc = course['varDesc'];
                    var varCoverInfo = course['varCoverInfo'];
                    if(courseName) $("#courseName").empty().html(courseName);
                    if(courseDesc) {}$("#courseDesc").empty().html(courseDesc);
                    if(varCoverInfo){
                        studentStudy.coverINfoUrl = varCoverInfo;
                    }

                    // 加载附件
                    studentStudy.getAttachment();
                }
            }
        });
    }

    studentStudy.getAttachment = function(){
        var params = {
            'courseId': studentStudy.courseId
        };
        $.ajax({
            url: studentStudy.basePath + "popup/getAttachment",
            data: params,
            type: "post",
            dataType:"json",
            success:function(data) {
                //console.log(data);
                var code = data.code;
                if("10000" == code){
                    var attachments = data['result'];
                    if(null == attachments || typeof (attachments) == 'undefined'|| attachments.length == 0) {
                        $("#show_list_video").empty().html("<li class=\"empty\">暂无视频</li>");
                        $("#show_list_doc").empty().html("<li class=\"empty\">暂无文档</li>");
                        return;
                    }
                    studentStudy.handlerAttachment(attachments);
                }
            }
        });
    }

    studentStudy.handlerAttachment = function (attachments){
        var len = attachments.length;
        var attachment = new Object(), varExt = "";
        var attachment_video = [];var attachment_doc = [];
        for(var i=0; i<len; i++) {
            attachment = attachments[i];
            varExt = attachment['varExt'];
            if(varExt == 'doc' || varExt == 'docx' || varExt == 'xlsx' || varExt == 'xls' || varExt == 'ppt' || varExt == 'pptx'|| varExt == 'pdf') {
                attachment_doc.push(attachment);continue;
            }
            if(varExt == 'flv' || varExt == 'mp4' || varExt == 'swf' || varExt == "mp3")  {
                attachment_video.push(attachment);continue;
            }
        }

        var inner_video = "", inner_doc = "";
        var attachment_video_length = attachment_video.length;
        var attachment_doc_length = attachment_doc.length;

        if(0 == attachment_video_length) {
            $("#show_list_video").empty().html("<li class=\"empty\">暂无视频</li>");
        } else {
            for(var j=0; j<attachment_video_length; j++) {
                inner_video += "<li><a  videoId=\""+attachment_video[j]['intId']+"\" fId=\""+attachment_video[j]['varFid']+"\">"+attachment_video[j]['varLocalName']+"</a></li>";
            }
            $("#show_list_video").empty().html(inner_video);
        }

        if(0 == attachment_doc_length) {
            $("#show_list_doc").empty().html("<li class=\"empty\">暂无文档</li>");
        } else {
            for(var k=0; k<attachment_doc_length; k++) {
                inner_doc += "<li><a  videoId=\""+attachment_doc[k]['intId']+"\" fId=\""+attachment_doc[k]['varFid']+"\">"+attachment_doc[k]['varLocalName']+"</a></li>";
            }
            $("#show_list_doc").empty().html(inner_doc);
        }

        // 视频或者文档点击播放事件处理
        $('#show_list_video li a').each(function (){
            var $a = $(this);

            $a.bind("click", function (){
                //记录视频播放位置
                studentStudy.savePosition();
                $('#show_list_video li a').removeClass("active"); $a.addClass("active");
                var $fId = $a.attr("fId");
                var $videoId = $a.attr("videoId");
                studentStudy.video_id = $videoId;

                setTimeout(function () {
                    studentStudy.playVideo($fId);
                },300)

            })
        });
        $('#show_list_doc li a').each(function (){
            var $a = $(this);
                $a.bind("click", function (){
                    $('#show_list_doc li a').removeClass("active"); $a.addClass("active");
                    var $fId = $a.attr("fId");
                    var $videoId = $a.attr("videoId");
                    studentStudy.video_id = $videoId;
                    studentStudy.playDoc($fId);
                })
        });

        // // 默认播放第一个视频
        // $('#show_list_video li a:eq(0)').trigger("click");

        //有视频课件优先视频课件
        if (0 != attachment_video_length ) {
            // 默认播放第一个视频
            $('#studentDoc').removeClass('active');
            $('#show_list_video li a:eq(0)').trigger("click");
        }else {
            //没有视频，直接播放第一个文档类课件
            $('#studentVideo').removeClass('active');
            var $this = $(this);
            $this.addClass('active').siblings('li').removeClass('active');
            $('.show_list div').eq(1).addClass('active').siblings('div').removeClass('active');
            $("#video").hide();
            $("#doc").show();
            $('.foot').addClass('mark');
            $('#show_list_doc li a:eq(0)').trigger("click");
        }
    }


    studentStudy.playVideo = function (fId){
        clearInterval(swfTime);
        // m3u8
        var params = {
            'fId': fId,
            'course_id': studentStudy.courseId,
            'user_id': studentStudy.userId,
            'video_id': studentStudy.video_id
        };
        $.ajax({
            url: studentStudy.basePath + "popup/m3u8",
            data: params,
            type: "post",
            dataType:"json",
            success:function(data) {
                //console.log(data);
                var code = data.code;
                if("10000" == code){

                    var url = data.result['url'];
                    if(url.indexOf(".swf")!=-1){
                        $("#swf").show();$("#video").hide();
                        studentStudy.swf(url);
                    }else{
                        $("#swf").hide();$("#video").show();
                        var position = data.result['lastPosition'];
                        url = encodeURI(url);
                        if(!url)return;

                        // mp3 需给一个底图
                        if(url.indexOf(".mp3")!=-1){
                            studentStudy.player.poster(studentStudy.coverINfoUrl)
                        }

                        studentStudy.player.src({
                            src: url,
                            type: 'application/X-mpegURL'
                        });
                        studentStudy.player.play();
                        // 进度条显示设置
                        common.setPlayProcess();
                        //视频从上次位置开始播放
                        if(position != 0){
                            setTimeout(function(){
                                studentStudy.player.currentTime(parseInt(position));
                            },300);
                        }

                        setTimeout(function(){
                            studentStudy.video_time = parseInt(studentStudy.player.duration());
                        },300);
                    }
                }
            }
        });
    }

    studentStudy.swf = function (srcStr) {
        clearInterval(studentStudy.timer);
        flowplayer("swf", srcStr, {
            clip: {
                autoPlay: true,
                autoBuffering: true
            },
            plugins: {
                controls: {
                    bottom: 0, //功能条距底部的距离
                    height: 24, //功能条高度
                    zIndex: 1000000,
                    //fontColor: '#ffffff',
                    //timeFontColor: '#333333',
                    playlist: false, //上一个、下一个按钮
                    play: true, //开始按钮
                    volume: true, //音量按钮
                    mute: true, //静音按钮
                    stop: true, //停止按钮
                    fullscreen: true, //全屏按钮
                    scrubber: true, //进度条
                    time: true, //是否显示时间信息
                    autoHide: false, //功能条是否自动隐藏
                    //backgroundColor: '#aedaff', //背景颜色
                    //backgroundGradient: [0.1, 0.1, 1.0], //背景颜色渐变度（等分的点渐变）
                    //opacity: 0.5, //功能条的透明度
                    //borderRadius: '30',//功能条边角
                }
            }
        });
        swfTime = setInterval(function () {
            studentStudy.time = studentStudy.time +1;
            $("#study_time").html(TimeUtil.getVideoTime(studentStudy.time));
        }, 1000);
    }

    studentStudy.playDoc = function (fId){
        clearInterval(swfTime);
        // m3u8
        var params = {
            'fId': fId
        };
        $.ajax({
            url: studentStudy.basePath + "popup/m3u8",
            data: params,
            type: "post",
            dataType:"json",
            success:function(data) {
                //console.log(data);
                var code = data.code;
                if("10000" == code){
                    var url = data.result['url'];
                    url = encodeURI(url);
                    if(!url)return;
                    var ifm = '<iframe id="iframe-doc" name="pdfView" src="'+ url +'" frameborder="0" style="width: 100%;height: 100%;" scrolling="no"></iframe>';

                    $("#doc").html(ifm);

                    // 开始文档计时
                    // setTimeout(function(){doc_time();},1000);
                }
            }
        });
    }

    studentStudy.formatSeconds = function (a){
        if(0 >=a)
            return "00时" + "00分" + "00秒";
        var hh = parseInt(a/3600);
        if(hh < 10) hh = "0" + hh;
        var mm = parseInt((a - hh*3600)/60);
        if(mm < 10) mm = "0" + mm;
        var ss = parseInt((a - hh*3600)%60);
        if(ss < 10) ss = "0" + ss;
        var result = hh + "时" + mm + "分" + ss + "秒";
        if(a > 0)
            return result;
        return "00时" + "00分" + "00秒";
    }

    // 檢測瀏覽器是否支持hls播放
    window.hlsSupportCallback = function (flag){
        if(!flag) { // 不支持
            studentStudy.player.pause();
            clearInterval(studentStudy.timer);
            $("#study_time").html(studentStudy.formatSeconds(0));
            studentStudy.time = 0;
            layer.open({
                type:1,
                title: false, // 不显示标题栏
                closeBtn: false,
                area: "600px",
                shade: 0.3,
                id: "layer-hls-support", // 设置id, 防止重复弹出
                resize: false,
                btn:["知道了"],
                btnAlign: "c",
                moveType: 1,
                content: "<div style='padding:50px;line-height:22px;background-color:#393D49;color:#fff;font-weight:300'>经系统检测,您的浏览器版本过低,无法完美支持视频播放<br>推荐您安装360安全浏览器&nbsp;&nbsp;&nbsp;<a href='//se.360.cn' target='_blank' style='color: rgb(0, 156, 75);'>点击下载</a></div>",
                yes: function(layero) {
                    layer.close(layero);
                }
            });
        }
    };
/*
* 通过video。js库来做计时功能
* */
window.studentStudyTime = function (time) {
    studentStudy.time = time;
    studentStudy.video_time = time;
    if( time !== 0 && (time % 300) === 0 ){
        studentStudy.player.pause();
        var index = layer.alert('您已经五分钟没有操作了，请确定是否继续学习 :-D',{title:'温馨提示:'},function(){
            studentStudy.player.play();
            layer.close( index );
        })
    }
    studentStudy.time = parseInt(studentStudy.doc_time) + parseInt(studentStudy.video_time);
    $("#study_time").html(studentStudy.formatSeconds(parseInt(studentStudy.time)));
}

//记录视频播放位置
studentStudy.savePosition = function () {
    $('#show_list_video li a').each(function (){
        if($(this).hasClass('active')){
            //视频播放进度
            var last_position = studentStudy.player.currentTime();
            var $last_position = last_position - studentStudy.player.duration();

            if($last_position >= 0){
                last_position = 0;
            }
            var param = {
                'course_id': studentStudy.courseId,
                'user_id': studentStudy.userId,
                'video_id': $(this).attr("videoId"),
                'study_time': parseInt(last_position)
            };

            saveVideoPosition(param);
        }
    })
}


//获取视频播放位置
studentStudy.getPosition = function (fid) {
    var param = {
        'course_id': studentStudy.courseId,
        'user_id': studentStudy.userId,
        'video_id': studentStudy.video_id,
        'fid': fid
    };
    getVideoPosition(param);
}


function feed_back() {
    var url = encodeURI(window.location.href);
    var feed_back_url = appPath + "/feedback?url=" + url;
    window.open(feed_back_url)
}

// 文档计时
var doc_time1 = null;
function doc_time() {

    if(doc_time1 != null){
        window.clearInterval(doc_time1);
    }
    studentStudy.doc_time = parseInt(studentStudy.doc_time)+ parseInt(1);
    studentStudy.time = parseInt(studentStudy.doc_time) + parseInt(studentStudy.video_time);
    $("#study_time").html(studentStudy.formatSeconds(parseInt(studentStudy.time)));
    // 执行计时器
    doc_time1 = window.setInterval("doc_time()",1000);
}



